 <template>
  
  <van-nav-bar
  title="登录"
  left-text="返回"
  left-arrow
  @click-left="onClickLeft"
/>
  <div style="text-align: center;">
    <van-image round  width="100px"  height="100px"    src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"/>
    <van-field v-model="phone" label="手机号" placeholder="请输入手机号" />
    <van-field
        v-model="sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendmes">发送验证码</van-button>
        </template>
      </van-field>

    <van-button type="primary" @click="login" style=" width: 100%; margin-top: 20px;">登录</van-button>
  </div>
 </template>
<script lang="ts" >
import { ref,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { showSuccessToast, showFailToast } from 'vant';

export default {
  setup() {
    const router=useRouter();
    const phone = ref('');
    const sms = ref('');
    const sendmes=()=>{
      axios.post('http://127.0.0.1:8000/zhxy/send/', { phone: phone.value })
        .then(response => {
          if (response.data.code=200) {
            console.log(response.data);
            showSuccessToast('发送成功');
            setTimeout(()=>{
              alert("验证码为"+response.data.data)
            },2000)
          } else {
            showFailToast('发送失败');
          }
        })
        .catch(error => {
          console.error(error);
        });
    }

    const login = () => {
      axios.post('http://127.0.0.1:8000/zhxy/login/', { phone: phone.value, code: sms.value })
        .then(response => {
          if (response.data.code == 200) {
            localStorage.setItem('token', response.data.data.token);
            localStorage.setItem('userid', response.data.data.userid);
            localStorage.setItem('username', response.data.data.username);
            onClickLeft();
          } else {
            alert('登录失败');
          }
        })
        .catch(error => {
          console.error(error);
        });
    };
    const onClickLeft = () => history.back();
    return {
      router,
      phone,
      sms,
      sendmes,
      login,
      onClickLeft,
    };
  },
};

</script>